package com.xuecheng.ucenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.ucenter.feignclient.CheckCodeClient;
import com.xuecheng.ucenter.mapper.XcUserMapper;
import com.xuecheng.ucenter.model.dto.AuthParamsDto;
import com.xuecheng.ucenter.model.dto.XcUserExt;
import com.xuecheng.ucenter.model.po.XcUser;
import com.xuecheng.ucenter.service.AuthService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

@Service("password_authservice")
public class PasswordAuthServiceImpl implements AuthService {

    @Autowired
    private XcUserMapper xcUserMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private CheckCodeClient checkCodeClient;

    @Override
    public XcUserExt execute(AuthParamsDto authParamsDto) {

        //因为此方法是针对的校验用户的名称 密码 和验证码 所以由checkcode和checkcodekey
        String checkcode = authParamsDto.getCheckcode();
        String checkcodekey = authParamsDto.getCheckcodekey();
        if(StringUtils.isEmpty(checkcode) || StringUtils.isEmpty(checkcodekey)){
            throw new RuntimeException("请输入验证码");
        }
        //验证码的校验
        Boolean verify = checkCodeClient.verify(checkcodekey, checkcode);
        if(verify==null || !verify){
            throw new RuntimeException("验证码输入错误");
        }


        String username = authParamsDto.getUsername();
        //根据用户名查询用户的信息 也就是loadUserByUsername这个方法的真实用意
        XcUser xcUser = xcUserMapper.selectOne(new LambdaQueryWrapper<XcUser>().eq(XcUser::getUsername, username));

        if(xcUser==null){
            throw new RuntimeException("账号不存在");
        }


        //数据库里面的密码是通过加密后的 所以如果要和用户输入的明文密码做校验就需要通过passwordEncoder的matches方法
        String passwordDb = xcUser.getPassword();

        String password = authParamsDto.getPassword();

        boolean matches = passwordEncoder.matches(password, passwordDb);
        if(!matches){
            throw new RuntimeException("账号或密码错误");
        }

        XcUserExt xcUserExt = new XcUserExt();
        BeanUtils.copyProperties(xcUser,xcUserExt);

        return xcUserExt;
    }
}
